package orm.infrastructure.converters;

import orm.er.PersonMock;
import orm.infrastructure.interfaces.IMockConverter;
import orm.infrastructure.interfaces.IValidable;

import java.util.Dictionary;
import java.util.Hashtable;

/**
 * Created with IntelliJ IDEA.
 * User: Awake
 * Date: 03.05.12
 * Time: 17:41
 * To change this template use File | Settings | File Templates.
 */
public class APersonConverter implements IMockConverter {

    private static final String ID_FIELD = "id";
    private static final String FNAME_FIELD = "FName";
    private static final String LNAME_FIELD = "LName";
    private static final int APERSON_FIELDS_COUNT = 3;

    @Override
    public Dictionary<String, Object> toDictionary(IValidable mock) {
        PersonMock personMock = (PersonMock) mock;
        if (personMock.isNullable())
            throw new NullPointerException();

        Dictionary<String, Object> dictionary = new Hashtable<String, Object>(APERSON_FIELDS_COUNT);
        dictionary.put(ID_FIELD, personMock.getID());
        dictionary.put(FNAME_FIELD, personMock.getFName());
        dictionary.put(LNAME_FIELD, personMock.getLName());

        return dictionary;
    }

    @Override
    public IValidable toObject(Dictionary<String, Object> dictionary) {

        if (dictionary.isEmpty())
            throw new NullPointerException();

        PersonMock mock = new PersonMock();

        if (dictionary.get(ID_FIELD) != null) {
            mock.setID((Integer) dictionary.get(ID_FIELD));
        }
        if (dictionary.get(FNAME_FIELD) != null) {
            mock.setFName((String) dictionary.get(FNAME_FIELD));
        }
        if (dictionary.get(LNAME_FIELD) != null) {
            mock.setLName((String) dictionary.get(LNAME_FIELD));
        }

        return mock;
    }
}
